package com.atguigu.tingshu.order.strategy.impl;
import java.math.BigDecimal;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.order.OrderDerate;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.service.OrderDerateService;
import com.atguigu.tingshu.order.service.OrderDetailService;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.google.common.collect.Lists;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.order.strategy.SaveOrderStrategy;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@Slf4j
public class WeiXinSaveOrderStrategy implements SaveOrderStrategy {

    @Autowired
    private OrderInfoService orderInfoService ;

    @Autowired
    private OrderDetailService orderDetailService ;

    @Autowired
    private OrderDerateService orderDerateService ;

    @Autowired
    private RedissonClient redissonClient ;

    @Transactional
    @Override
    public OrderInfoVo saveOrder(OrderInfoVo orderInfoVo) {

        // 保存订单相关数据到对应的数据库表中： 保存订单基本数据(order_info)、保存订单的明细数据（order_detail）、保存订单的减免明细(order_derate)
        this.saveOrderInfoAndOrderDetailAndOrderDerate(orderInfoVo , orderInfoService ,
                orderDetailService ,
                orderDerateService);

        return orderInfoVo;
    }

    private void sendDelayMessage(String tradeNo) {

        // 获取阻塞队列对象
        RBlockingDeque<String> blockingDeque = redissonClient.getBlockingDeque(RedisConstant.QUEUE_ORDER_CANCEL_PREFIX);
        RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
        delayedQueue.offer(tradeNo , SystemConstant.ORDER_CANCEL_TIMEOUT , TimeUnit.SECONDS);
        log.info("延迟任务发布成功了...orderNo:{} " , tradeNo);

    }

    @Override
    public String getPayway() {
        return SystemConstant.ORDER_PAY_WAY_WEIXIN;     // 微信支付方式，1101
    }

    @Override
    public void saveOrderAfterProcess(OrderInfoVo orderInfoVo) {
        this.sendDelayMessage(orderInfoVo.getTradeNo()) ;
    }
}
